package com.andaily.domain.thing;

import com.andaily.domain.dto.thing.ThingAmountDto;
import com.andaily.domain.shared.DateUtils;
import com.andaily.domain.shared.security.SecurityUtils;
import com.andaily.web.context.BeanProvider;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Date: 13-6-15 下午10:17
 *
 * @author Shengzhao Li
 */
public class ThingAmountDtoLoader {

    private static ThingRepository thingRepository() {
        return BeanProvider.getBean(ThingRepository.class);
    }

    public ThingAmountDtoLoader() {
    }

    public ThingAmountDto load() {
        ThingAmountDto thingAmountDto = new ThingAmountDto();
        if (!SecurityUtils.isLogged()) {
            return thingAmountDto;
        }
        final String currentUserGuid = SecurityUtils.currentUserGuid();
        //event amount
        loadEventAmount(thingAmountDto, currentUserGuid);
        // history amount
        loadHistoryAmount(thingAmountDto, currentUserGuid);
        //monitoring amount
        loadMonitoringAmount(thingAmountDto, currentUserGuid);
        //warn amount
        loadWarningAmount(thingAmountDto, currentUserGuid);

        return thingAmountDto;
    }

    private void loadWarningAmount(ThingAmountDto thingAmountDto, String currentUserGuid) {
        final Date now = DateUtils.now();
        int warnAmount = thingRepository().amountOfWarning(currentUserGuid, now, ThingStatus.CREATED);
        thingAmountDto.setWarningAmount(warnAmount);
    }

    private void loadMonitoringAmount(ThingAmountDto thingAmountDto, String currentUserGuid) {
        int monitoringAmount = thingRepository().amountThingsByStatus(currentUserGuid, ThingStatus.PENDING, ThingStatus.CREATED);
        thingAmountDto.setMonitoringAmount(monitoringAmount);
    }

    private void loadHistoryAmount(ThingAmountDto thingAmountDto, String currentUserGuid) {
        int historyAmount = thingRepository().amountThingsByStatus(currentUserGuid, ThingStatus.END, ThingStatus.CANCEL);
        thingAmountDto.setHistoryAmount(historyAmount);
    }

    private void loadEventAmount(ThingAmountDto thingAmountDto, String currentUserGuid) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userGuid", currentUserGuid);
        thingAmountDto.setEventAmount(thingRepository().totalEvents(params));
    }
}
